package caculate.linkedList;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-04-10 22:47
 **/
public class addTwoNumbers {

    public static void main(String[] args) {
        ListNode l1 = create(9, 7);
        ListNode l2 = create(9, 4);
        ListNode listNode = addTwoNumbers(l1, l2);
        while (listNode != null) {
            System.out.print(listNode.val);
            listNode = listNode.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode n1 = l1;
        ListNode n2 = l2;

        ListNode result = null;
        ListNode cache = null;

        boolean jinwei = false;
        while (jinwei || n1 != null || n2 != null) {
            int v1 = n1 == null ? 0 : n1.val;
            int v2 = n2 == null ? 0 : n2.val;

            int val = v1 + v2 + (jinwei ? 1 : 0);
            if (val >= 10) {
                jinwei = true; // 进位
                val = val - 10;
            } else {
                jinwei = false;
            }

            if (result == null) {
                result = new ListNode(val, null);
                cache = result;
            } else {
                ListNode ln = new ListNode(val, null);
                cache.next = ln;
                cache = ln;
            }

            if (n1 != null) n1 = n1.next;
            if (n2 != null) n2 = n2.next;
        }

        return result;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

   public static ListNode create(int num, int size){
       ListNode result = new ListNode(num, null);
       ListNode cache = result;
       for (int i = 1; i < size; i++) {
           ListNode ln = new ListNode(num, null);
           cache.next = ln;
           cache = ln;
       }

       return result;
    }

}
